var chat = [];
chat.push({ id: 1, svrId: 1, title: "客服1", createTime: "2021-01-01 10:00:00", msg: [] });
chat[0].msg.push({ id: 1, svrId: 1, createTime: "2021-01-01 10:00:00", isUser: true, content: "你好" });
chat[0].msg.push({ id: 2, svrId: 2, createTime: "2021-01-01 10:00:01", isUser: false, content: "你好，我是机器人。" });
chat[0].msg.push({ id: 3, svrId: 3, createTime: "2021-01-01 10:00:02", isUser: true, content: "你好，我是机器人。" });
chat[0].msg.push({ id: 4, svrId: 4, createTime: "2021-01-01 10:00:03", isUser: false, content: "你好，我是机器人。" });
chat.push({ id: 2, svrId: 2, title: "客服2", createTime: "2021-01-01 10:00:04", msg: [] });
chat[1].msg.push({ id: 1, svrId: 1, createTime: "2021-01-01 10:00:04", isUser: true, content: "你好，我是机器人。" });
chat[1].msg.push({ id: 2, svrId: 2, createTime: "2021-01-01 10:00:05", isUser: false, content: "你好，我是机器人。" });
chat[1].msg.push({ id: 3, svrId: 3, createTime: "2021-01-01 10:00:06", isUser: true, content: "你好，我是机器人。" });
chat[1].msg.push({ id: 4, svrId: 4, createTime: "2021-01-01 10:00:07", isUser: false, content: "你好，我是机器人。" });
chat.push({ id: 3, svrId: 3, title: "客服3", createTime: "2021-01-01 10:00:08", msg: [] });
chat[2].msg.push({ id: 1, svrId: 1, createTime: "2021-01-01 10:00:08", isUser: true, content: "你好，我是机器人。" });
chat[2].msg.push({ id: 2, svrId: 2, createTime: "2021-01-01 10:00:09", isUser: false, content: "你好，我是机器人。" });
chat[2].msg.push({ id: 3, svrId: 3, createTime: "2021-01-01 10:00:10", isUser: true, content: "你好，我是机器人。" });
chat[2].msg.push({ id: 4, svrId: 4, createTime: "2021-01-01 10:00:11", isUser: false, content: "你好，我是机器人。" });
//console.log(chat);

function setInputWidth() 
{
  var messages = document.getElementById("chat-container-messages");
  var input = document.getElementById("chat-container-input");
  input.style.width = messages.offsetWidth + "px";
}

setInputWidth();
window.addEventListener("resize", setInputWidth);

document.getElementById("chat-container-input-text").addEventListener("input", function() 
{
  this.style.height = "auto";
  this.style.height = this.scrollHeight + "px";
});

document.getElementById("chat-container-input-text").addEventListener("input", function() 
{
  if (this.scrollHeight > 288)
    this.style.overflowY = "scroll";
  else
    this.style.overflowY = "hidden";
});

/*
document.getElementById("sendButton").addEventListener("click", function() 
{
  try 
  {
    const options =
    {
    method: "POST",
      headers:{ "Content-Type": "application/json"},
      body: JSON.stringify({ prompt: "你好" })
    };
    
    const promise = fetch("http://192.168.1.2/ai", options);
    //const promise = fetch("http://192.168.a1.2:8080/ai", options);
    promise.then(response =>
    {
    if (!response.ok)
      {
    throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      var chatContainer = document.getElementById("chat-container");
      var message = document.createElement("div");
      message.classList.add("messages");
      chatContainer.appendChild(message);

const reader = response.body.getReader();
      const decoder = new TextDecoder();
  // 递归读取数据
  function readChunk() {
    return reader.read().then(({ done, value }) => {
      if (done)
      {
        //console.log('Stream complete');
        return;
      }

      // 处理当前数据块（value 是 Uint8Array）
      const chunk = decoder.decode(value, { stream: true });
      //console.log('Received chunk:', chunk);
      message.textContent += chunk;

      // 继续读取下一个块
      return readChunk();
    });
}
		
        return readChunk();
	   });
	   
		
		 
  
//        const reader = response.body.getReader();
//        let assistantMessage = '';
//  
//        // 使用块级作用域隔离每次迭代的变量
//        while (true) {
//          const { done, value } = await reader.read();
//          if (done) break;
//          const chunk = new TextDecoder().decode(value);
//          assistantMessage += chunk;
//  
//          // 关键修复：捕获当前迭代的 assistantMessage 值
//          const currentMessage = assistantMessage;
//          setMessages((prev) => {
//            const lastMsg = prev[prev.length - 1];
//            if (lastMsg && !lastMsg.isUser) {
//              return [
//                ...prev.slice(0, -1),
//                { text: currentMessage, isUser: false }
//              ];
//            }
//            return [...prev, { text: currentMessage, isUser: false }];
//          });
//        }
   } catch (error) 
   {
	   console.log(error);
   }
//	xhr.open("POST", "http:192.168.1.2/ai", true);
//	xhr.setRequestHeader("Content-Type", "application/json");
//	xhr.onreadystatechange = function() {
//		if (xhr.readyState === 4 && xhr.status === 200) {
//			console.log('Response:', xhr.responseText);
//		}
//	};
//	
//	xhr.send(JSON.stringify({ prompt: "你好" }));
});

//function addMessage(message, type) {
//    let messagesDiv = document.querySelector('.messages');
//    let messageElement = document.createElement('div');
//    messageElement.classList.add('message', type);
//    messageElement.textContent = message;
//    messagesDiv.appendChild(messageElement);
//    messagesDiv.scrollTop = messagesDiv.scrollHeight;
//}
//
//// 模拟接收消息
//setTimeout(function() {
//    addMessage('你好！这是接收到的消息。', 'received');
//}, 2000);

*/